/*
 * @Author: Xujianchen
 * @Date: 2024-07-05 09:33:23
 * @LastEditors: xujianchen
 * @LastEditTime: 2024-07-05 09:39:51
 * @Description: 发送验证码
 */
import { ElMessage } from 'element-plus'
import { isPhone } from '@/utils/regexp'

export default function useSendCode() {
  const countdown = ref(0)
  let timer = null

  const disabled = computed(() => countdown.value > 0)
  const buttonText = computed(() => {
    const time = countdown.value
    return time > 0 ? `${time}s后重新发送` : '发送验证码'
  })

  onBeforeUnmount(() => timer && clearInterval(timer))

  function sendCode(phone) {
    if (!isPhone(phone)) {
      return ElMessage.warning('手机号格式不正确')
    }
    if (countdown.value > 0) return

    countdown.value = 60
    timer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(timer)
      }
    }, 1000)
  }

  return {
    countdown,
    disabled,
    buttonText,
    sendCode,
  }
}
